import Vue from 'vue';

Vue.directive('dialog-drag', {
  bind(el, binding, vnode, oldVnode) {
    const dialogEle = el.querySelector('.el-dialog');

    const dialogHeaderEle = el.querySelector('.el-dialog__header');
    dialogHeaderEle.style.cursor = 'move';

    dialogHeaderEle.onmousedown = ($event) => {
      let e = $event || window.event;
      e.preventDefault();

      let dialogEleWidth = dialogEle.offsetWidth; // dialog宽度
      let dialogEleHeight = dialogEle.offsetHeight; // dialog高度

      let screenWidth = document.documentElement.clientWidth; // 窗口可视宽度
      let screenHeight = document.documentElement.clientHeight; // 窗口可视高度
      
      let moveMinXSpace = Math.ceil(dialogEleWidth / 2); // X轴反方向可移动最大空间
      let moveMaxXSpace = screenWidth - dialogEleWidth + Math.floor(dialogEleWidth / 2); // X轴正方向可移动最大空间
      let moveMinYSpace = Math.ceil(dialogEleHeight / 2); // Y轴正方向可移动最大空间
      let moveMaxYSpace = screenHeight - dialogEleHeight + Math.floor(dialogEleHeight / 2); // y轴反方向可移动最大空间

      let initialX = e.clientX;
      let initialY = e.clientY;

      let dialogOffsetLeft = dialogEle.offsetLeft;
      let dialogOffsetTop = dialogEle.offsetTop;

      document.onmousemove = function($event) {
        let e = $event || window.event;
        e.preventDefault();

        let nowX = e.clientX;
        let nowY = e.clientY;

        let moveDistanceX = initialX - nowX;
        let moveDistanceY = initialY - nowY;

        let styleX = dialogOffsetLeft - moveDistanceX;
        let styleY = dialogOffsetTop - moveDistanceY;

        if (styleX >= moveMaxXSpace) {
          styleX = moveMaxXSpace;
        }
        if (styleY >= moveMaxYSpace) {
          styleY = moveMaxYSpace;
        }
        if (styleX <= moveMinXSpace) {
          styleX = moveMinXSpace;
        }
        if (styleY <= moveMinYSpace) {
          styleY = moveMinYSpace;
        }

        dialogEle.style.left = styleX + 'px';
        dialogEle.style.top = styleY + 'px';
      }
      document.onmouseup = function ($event) {
        let e = $event || window.event;
        e.preventDefault();

        document.onmousemove = null;
        document.onmouseup = null;
      };
    }
  }
})